import React from 'react';
import classNames from 'classnames';
import { formatMessage } from 'umi';
import { Button, message, Popconfirm, Tooltip } from 'antd';

import BizIcon from '@/components/BizIcon';
import { isSuccess } from '@/utils/request';
import If from '@/components/If';
import authHelper from '@/utils/auth/helper';

import { commonColumn } from '@/pages/SalaryManage/utils/TableUtil';
import ExcelListBaseModel from '@/pages/SalaryManage/SalaryCalculate/ImportExcel/ExcelListBaseModel';
import { goToSalaryBaseKpiLog, goToSalaryBaseKpiEdit } from '@/pages/SalaryManage/utils/pageNavigateUtil';
import {
    baseKpiDownload,
    deleteSalaryBaseKpi,
    getKpiSalaryItems,
    queryBaseKpi,
    queryBaseKpiLastImportYearMonth
} from '@/services/salaryManage/salaryCalculate';
import AutoDivider from '@/pages/SalaryManage/components/AutoDivider';
import salaryStyle from '@/pages/SalaryManage/salaryManage.less';
import EmptyPlaceHolder from '@/pages/SalaryManage/components/EmptyPlaceHolder';

const salaryBaseKpiModel = ExcelListBaseModel({
    namespace: 'salaryBaseKpiModel',
    queryService: queryBaseKpi,
    initService: queryBaseKpiLastImportYearMonth
});

salaryBaseKpiModel.state.goToLog = goToSalaryBaseKpiLog;
salaryBaseKpiModel.state.goToEdit = goToSalaryBaseKpiEdit;
salaryBaseKpiModel.state.columns = (pagination, { onEdit, onDelete }) => [
    {
        // 序号
        title: formatMessage({ id: 'salaryBaseKpi.table.sn' }),
        dataIndex: 'sn',
        render(text, record, index) {
            return `${(pagination.current - 1) * pagination.pageSize + index + 1}`;
        },
        align: 'center',
        width: 80
    },
    commonColumn({
        // 工号
        title: formatMessage({ id: 'salaryBaseKpi.table.employeeNo' }),
        dataIndex: 'employeeNo',
        align: 'left',
        width: 120
    }),
    commonColumn({
        // 姓名
        title: formatMessage({ id: 'salaryBaseKpi.table.name' }),
        dataIndex: 'name',
        align: 'left',
        width: 132
    }),
    commonColumn({
        // 状态
        title: formatMessage({ id: 'salaryBaseKpi.table.status' }),
        dataIndex: 'workState',
        align: 'center',
        width: 80
    }),
    commonColumn({
        // 部门
        title: formatMessage({ id: 'salaryBaseKpi.table.department' }),
        dataIndex: 'department',
        width: 180
    }),
    {
        // 所属月份
        title: formatMessage({ id: 'salaryBaseKpi.table.period' }),
        dataIndex: 'period',
        render(text, record /* , index */) {
            const arr = [];

            if (record.year != null) {
                arr.push(record.year);
            }

            if (record.month != null) {
                arr.push(record.month < 10 ? `0${record.month}` : record.month);
            }

            return arr.length === 0 ? <EmptyPlaceHolder /> : arr.join('-');
        },
        width: 95
    },
    commonColumn({
        // 绩效薪资类型
        title: formatMessage({ id: 'salaryBaseKpi.table.salaryItemName' }),
        dataIndex: 'salaryItemName'
    }),
    {
        // 开始区间
        title: formatMessage({ id: 'salaryBaseKpi.table.startPeriod' }),
        dataIndex: 'startPeriod',
        render(text, record) {
            return record.kpiStartYear && record.kpiStartMonth ? (
                `${record.kpiStartYear}-${record.kpiStartMonth < 10 ? '0' : ''}${record.kpiStartMonth}`
            ) : (
                <EmptyPlaceHolder />
            );
        },
        width: 95
    },
    {
        // 结束区间
        title: formatMessage({ id: 'salaryBaseKpi.table.endPeriod' }),
        dataIndex: 'endPeriod',
        render(text, record) {
            return record.kpiEndYear && record.kpiEndMonth ? (
                `${record.kpiEndYear}-${record.kpiEndMonth < 10 ? '0' : ''}${record.kpiEndMonth}`
            ) : (
                <EmptyPlaceHolder />
            );
        },
        width: 95
    },
    commonColumn({
        // 绩效系数
        title: formatMessage({ id: 'salaryBaseKpi.table.kpiNum' }),
        dataIndex: 'kpiNum',
        align: 'right',
        width: 95
    }),
    commonColumn({
        // 补充说明
        title: formatMessage({ id: 'salaryBaseKpi.table.remark' }),
        dataIndex: 'remark'
    }),
    {
        title: '操作',
        dataIndex: 'v_operate',
        fixed: 'right',
        width: 100,
        render(text, record) {
            return (
                <AutoDivider>
                    <If condition={authHelper.checkCode('finance:salary:computation:import:kpi:edit')}>
                        <Tooltip title="编辑">
                            <Button
                                className={classNames(salaryStyle.operateIcon)}
                                onClick={() => onEdit(record)}
                                disabled={!!record?.payrollIfProcessed}
                            >
                                <BizIcon type="listfunction_edit_icon_default" />
                            </Button>
                        </Tooltip>
                    </If>

                    <If condition={authHelper.checkCode('finance:salary:computation:import:kpi:del')}>
                        <Popconfirm
                            title={`是否确定删除【${record.name}】的绩效系数信息`}
                            placement="bottomRight"
                            onConfirm={() => onDelete(record)}
                            disabled={!!record?.payrollIfProcessed}
                        >
                            <Tooltip title="删除" placement="top">
                                <Button
                                    className={classNames(salaryStyle.operateIcon)}
                                    disabled={!!record?.payrollIfProcessed}
                                >
                                    <BizIcon type="DeleteIcon" />
                                </Button>
                            </Tooltip>
                        </Popconfirm>
                    </If>
                </AutoDivider>
            );
        }
    }
];
salaryBaseKpiModel.state.kpiSalaryItems = [];
salaryBaseKpiModel.state.salaryItemId = null;
salaryBaseKpiModel.reducers.setKpiSalaryItems = (state, action) => ({
    ...state,
    kpiSalaryItems: action.payload
});

salaryBaseKpiModel.reducers.setSalaryItemId = (state, action) => ({
    ...state,
    salaryItemId: action.payload
});

salaryBaseKpiModel.effects.downloadTemplate = function* downloadExcel({ payload }, { call }) {
    return yield call(baseKpiDownload, payload);
};

salaryBaseKpiModel.effects.deleteSalaryBaseKpi = function* deleteBaseKpi(
    { payload, callback, currentRecord },
    { call, put }
) {
    yield put({
        type: 'setMultiStore',
        payload: { pageLoading: true }
    });
    const response = yield call(deleteSalaryBaseKpi, { id: payload });
    yield put({
        type: 'setMultiStore',
        payload: { pageLoading: false }
    });

    if (isSuccess(response)) {
        message.success(`【${currentRecord.name}】的绩效系数删除成功`);
        yield put({ type: 'search' });
    } else {
        message.error(response.msg);
    }

    if (callback) {
        callback(response);
    }
};

salaryBaseKpiModel.effects.fetchKpiSalaryItems = function* fetchKpiSalaryItems(state, { call, put }) {
    const response = yield call(getKpiSalaryItems, state.payload?.organizationCode);

    if (isSuccess(response)) {
        yield put({
            type: 'setKpiSalaryItems',
            payload: response.data
        });
        yield put({
            type: 'setSalaryItemId',
            payload: null
        });
    }
};

export default salaryBaseKpiModel;
